package com.liguang.rcs.admin.web.user;

import com.liguang.rcs.admin.db.entity.DodmsUserEntity;
import com.liguang.rcs.admin.permission.RequiresPermissionsDesc;
import com.liguang.rcs.admin.service.DodmsUserService;
import com.liguang.rcs.admin.util.RegexUtil;
import com.liguang.rcs.admin.util.ResponseCode;
import com.liguang.rcs.admin.util.bcrypt.BCryptPasswordEncoder;
import com.liguang.rcs.admin.util.copy.BeanUtils;
import com.liguang.rcs.admin.util.response.PageableBody;
import com.liguang.rcs.admin.util.response.ResponseObject;
import com.liguang.rcs.admin.validator.Order;
import com.liguang.rcs.admin.validator.Sort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.liguang.rcs.admin.util.ResponseCode.USER_INVALID_ACCOUNT;

@RestController
@RequestMapping("/admin/admin")
@Validated
@Api(tags = "用户管理API")
@Slf4j
public class UserMangerController {
    private static final Log LOG = LogFactory.getLog(UserMangerController.class);

    @Autowired
    private DodmsUserService userService;

    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu={"系统管理" , "用户管理"}, button="查询")
    @ApiOperation(value = "查询用户列表")
    @GetMapping("/list")
    public ResponseObject<PageableBody<UserVO>> list(String username,
                                                     @RequestParam(defaultValue = "1") Integer page,
                                                     @RequestParam(defaultValue = "10") Integer limit,
                                                     @Sort @RequestParam(defaultValue = "add_time") String sort,
                                                     @Order @RequestParam(defaultValue = "desc") String order) {
        return ResponseObject.success(userService.querySelective(username, page, limit, sort, order));
    }

    private ResponseObject validate(UserVO user, boolean isUpdate) {
        String name = user.getUserName();
        if (StringUtils.isEmpty(name)) {
            return ResponseObject.badArgument();
        }
        if (!RegexUtil.isUsername(name)) {
            return ResponseObject.fail(USER_INVALID_ACCOUNT, "管理员名称只能6-20个字符");
        }
        String password = user.getPassword();
        if (!isUpdate && (StringUtils.isEmpty(password) || password.length() < 6)) {
            return ResponseObject.fail(USER_INVALID_ACCOUNT, "管理员密码长度不能小于6");
        }
        return null;
    }

    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu={"系统管理" , "用户管理"}, button="添加")
    @ApiOperation(value = "添加用户")
    @PostMapping("/create")
    public ResponseObject create(@RequestBody UserVO user) {
        ResponseObject error = validate(user, false);
        if (error != null) {
            return error;
        }

        String username = user.getUserName();
        List<DodmsUserEntity> adminList = userService.findUser(username);
        if (adminList.size() > 0) {
            return ResponseObject.fail(ResponseCode.USER_NAME_EXIST, "管理员已经存在");
        }
        DodmsUserEntity entity = user.toEntity();
        String rawPassword = user.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        entity.setPassword(encodedPassword);
        userService.add(entity);
        return ResponseObject.success();
    }

    @RequiresPermissions("admin:admin:read")
    @RequiresPermissionsDesc(menu={"系统管理" , "用户管理"}, button="详情")
    @ApiOperation(value = "查询用户详情")
    @GetMapping("/read")
    public ResponseObject<UserVO> read(@RequestParam(value = "id") Long id) {
        DodmsUserEntity admin = userService.findById(id);
        return ResponseObject.success(UserVO.buildFrom(admin));
    }

    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu={"系统管理" , "用户管理"}, button="编辑")
    @ApiOperation(value = "更新用户信息")
    @PostMapping("/update")
    public ResponseObject update(@RequestBody UserVO user) {
        ResponseObject error = validate(user, true);
        if (error != null) {
            return error;
        }
        DodmsUserEntity entity;
        Long anotherAdminId = user.getId();
        if (anotherAdminId == null || (entity = userService.findById(anotherAdminId)) == null) {
            return ResponseObject.badArgument();
        }
        try {
            BeanUtils.copyProperties(user, entity);
        } catch (Exception ex) {
            log.error("update fail,", ex);
            return ResponseObject.serious();
        }
        userService.updateById(entity);
        return ResponseObject.success();
    }

    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu={"系统管理" , "用户管理"}, button="删除")
    @ApiOperation(value = "删除用户")
    @PostMapping("/delete")
    public ResponseObject delete(@RequestBody UserVO user) {
        Long anotherAdminId = user.getId();
        if (anotherAdminId == null) {
            return ResponseObject.badArgument();
        }

        // 管理员不能删除自身账号
        Subject currentUser = SecurityUtils.getSubject();
        DodmsUserEntity currentAdmin = (DodmsUserEntity) currentUser.getPrincipal();
        if (currentAdmin.getId().equals(anotherAdminId)) {
            return ResponseObject.fail(ResponseCode.USER_DELETE_NOT_ALLOWED, "管理员不能删除自己账号");
        }
        userService.deleteById(anotherAdminId);
        return ResponseObject.success();
    }
}
